package com.hxs.hxsserver.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期工具类
 *
 * @author Andi
 * @date 2021/01/13
 */
public class DateUtil {

    /**
     * 获取0点日期
     *
     * @param date 日期
     * @return {@link Date}
     */
    public static Date zeroDate(Date date) {
        if (date == null) {
            date = new Date();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }


    /**
     * 字符串转日期
     *
     * @param dateString 日期字符串
     * @param dateFormat 日期格式
     * @return {@link Date}* @throws ParseException 解析异常
     */
    public static Date stringToDate(String dateString, String dateFormat) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
        try {
            return simpleDateFormat.parse(dateString);
        } catch (ParseException e) {
            return null;
        }
    }


    /**
     * 日期转字符串
     *
     * @param date       日期
     * @param dateFormat 日期格式
     * @return {@link Date}* @throws ParseException 解析异常
     */
    public static String dateToString(Date date, String dateFormat) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
        return simpleDateFormat.format(date);
    }

    /**
     * 将 Date 转换为 LocalDateTime
     *
     * @param date
     * @return {@link LocalDateTime}
     */
    public static LocalDateTime convertToLocalDateTime(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * 计算两个时间相差天时分秒
     *
     * @param date1
     * @param date2
     * @return {@link String}
     */
    public static String getRemainingTime(LocalDateTime date1,LocalDateTime date2) {
        // 计算剩余时间
        Duration duration = Duration.between(date1, date2);
        long totalSeconds = duration.getSeconds();

        // 转换为天、小时、分钟、秒
        long d = totalSeconds / (24 * 3600);
        long h = (totalSeconds % (24 * 3600)) / 3600;
        long m = (totalSeconds % 3600) / 60;
        long s = totalSeconds % 60;
        if (d > 0) {
            return d + " d " + h + " h " + m + " m " + s + " s ";
        }
        if (h > 0) {
            return h + " h " + m + " m " + s + " s ";
        }
        if (m > 0) {
            return m + " m " + s + " s";
        }
        return s + " s";
    }
}
